import {generateName} from './upload.js';
import store from '@/store';
const db = uniCloud.database();
const collection=db.collection('admin-files');

export default {
	props: {
		filesLength:{
			type:Number,
			default:999
		},
		classify:{
			type:String
		},
		showModal:{
			type:Boolean,
			default:false
		}
	},
	data() {
		return {
			files:[],//文件
			inUpload:false,//是否正在全部上传
			filesIndex:0,//上传到第几个文件
			uploadFilesList:[],//所有上传文件列表
			uploadCassify:'',//上传时的文件目录
		}
	},
	computed: {
		tokenExpired(){
			return store.state.user.tokenExpired;
		}
	},
	methods:{
		//删除文件
		del(index){
			this.files.splice(index,1)
		},
		//预览图片
		previewImage(src){
			uni.previewImage({urls: src});
		},
		//上传全部
		uploadAll(){
			if(this.inUpload || this.files.length===0){
				return false;
			}
			const time =(new Date()).getTime()+600;
			if(time>this.tokenExpired){
				if(this.showModal){
					uni.showModal({
						title:"登录快超时了，不能完成上传"
					})
				}
				return;
			}
			this.inUpload=true;
			this.filesIndex=0;
			this.uploadFilesList=[]
			this.uploadCassify=this.classify;
			this.uploadFiles()
		},
		uploadFiles(){
			if(this.filesIndex>this.files.length-1){
				this.inUpload=false;
				if(this.showModal){
					uni.showModal({
						title:"上传完成"
					})
				}
				this.files=[]
				const list =this.uploadFilesList
				this.filesIndex=0
				this.$emit('upload-complete',list)
				return;
			}
			const filesIndex=this.filesIndex
			const item =this.files[filesIndex]
			this.filesIndex=filesIndex+1;
			this.uplaod(item).then(res=>{
				this.uploadFiles()
			}).catch(res=>{
				this.uploadFiles()
			})
		},
		uplaod(item){
			if(item.isUpload){
				return Promise.resolve()
			}
			return this.uploadFile(item)
		},
		uploadFile(item){
			return new Promise((resolve,reject)=>{
				if(item.isUpload){
					resolve()
				}
				this.$set(item,'isUpload',true)
				const self=this,
					filePath=item.src,
					{name}=item.fileInfo,
					cloudPath=generateName()+name;
				uniCloud.uploadFile({
					filePath,cloudPath,
					onUploadProgress: function(progressEvent) {
						const {loaded,total}=progressEvent
						const  percentCompleted = loaded/total*100
						self.$set(item,'progress',percentCompleted)
					}
				}).then(res=>{
					self.$set(item,'src',res.fileID)
					return Promise.resolve(res.fileID)
				}).then(fileID=>{
					const classify=self.uploadCassify||undefined;
					const data={name,cloudPath,fileID,classify,...item.fileInfo}
					collection.add(data)
					.then(res=>{
						self.$set(item,'progress',0)
						const {result}=res;
						const {id}=result;
						self.uploadFilesList.push({...data,_id:id})
						resolve(res)
					})
					.catch(res=>reject(res))
				}).catch(res=>reject(res))
			})
		},
		
	}
}